var bmap = require('../../libs/bmap-wx.min.js')
let APP = getApp();
let moreJs = require('../common/shoppingCat.js')
Page({
  data: {
    vipList: [{
        id: 'shucai',
        banner: "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2209846807,1303693616&fm=26&gp=0.jpg",
        gName: '西红柿2个',
        gPrice: '9.8',
        gNum: '约500g',
        gFormer: '45',
      },
      {
        id: 'shucai',
        banner: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1554304261741&di=bd157931a530c8aef02098288933c85d&imgtype=0&src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2Ffe2d5467b77067cb43131216e53e510a0774b3d7c67e-0WsabQ_fw658",
        gName: '新鲜猪肉',
        gNum: '500g',
        gPrice: '23',
        gFormer: '45',
      },
      {
        id: 'shuiguo',
        banner: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1554304261741&di=bd157931a530c8aef02098288933c85d&imgtype=0&src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2Ffe2d5467b77067cb43131216e53e510a0774b3d7c67e-0WsabQ_fw658",
        gName: '西红柿2个',
        gPrice: '9.8',
        gNum: '约500g',
        gFormer: '45',
      },
      {
        id: 'shucai',
        banner: "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2209846807,1303693616&fm=26&gp=0.jpg",
        gName: '西红柿2个',
        gPrice: '9.8',
        gNum: '约500g',
        gFormer: '45',
      },
      {
        id: 'shucai',
        banner: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1554304261741&di=bd157931a530c8aef02098288933c85d&imgtype=0&src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2Ffe2d5467b77067cb43131216e53e510a0774b3d7c67e-0WsabQ_fw658",
        gName: '新鲜猪肉',
        gNum: '500g',
        gPrice: '23',
        gFormer: '45',
      },
      {
        id: 'shuiguo',
        banner: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1554304261741&di=bd157931a530c8aef02098288933c85d&imgtype=0&src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2Ffe2d5467b77067cb43131216e53e510a0774b3d7c67e-0WsabQ_fw658",
        gName: '西红柿2个',
        gPrice: '9.8',
        gNum: '约500g',
        gFormer: '45',
      },


    ],
    detail: [],
    ak: "n967yNkgFeKQksfXfuWFIH2SuCbzoGbt", //密钥
    addressData: '', //位置信息
    isScroll: true, //可以向下滑动
    toView: 'hot', //初始展示的物品类型
    num: 1, //当前页
    ifnum: true, //是否还有新的页数
    headImgs: ['../../image/head-1.jpg', '../../image/head-2.jpg'],
    userID: null,
    showModal: true
  },


  onLoad: function (options) {
    let self = this;
    wx.login({
      success: res => {
        console.log(res);
        getApp().globalData.code = res.code;
        wx.getSetting({
          success: res => {
            console.log(res);
            if (!res.authSetting['scope.userInfo']) {
              wx.navigateTo({
                url: '../component/test/test'
              })
            } else {
              if (self.data.showModal) {
                wx.showModal({
                  title: '亲爱的邻居朋友们',
                  content: '为了给大家提供更优质的产品与服务，我们将调整水果类采购渠道，寻找更优质丰富的货源品种，在此期间将暂时下架水果类产品，感谢大家的支持和信任！',
                  success: function (res) {
                    self.setData({
                      showModal: false,
                    })
                  }
                })
              }
              wx.getUserInfo({
                success(res) {
                  console.log('------------------------------------');
                  console.log(res);
                  getApp().globalData.userInfo = res.userInfo;
                  getApp().globalData.nickName = res.userInfo.nickName;
                  wx.request({
                    url: 'https://localhost:80/user/login',
                    method: 'post',
                    data: {
                      code: getApp().globalData.code,
                      nickName: getApp().globalData.userInfo.nickName,
                      encryptedData: res.encryptedData,
                      iv: res.iv,
                      rawData: res.rawData,
                      signature: res.signature
                    },
                    success: res => {
                      console.log('获取用户信息成功');
                      getApp().globalData.userID = res.data.userId;
                      getApp().globalData.openID = res.data.userOpenid;
                      wx.setStorage({
                        key: 'userID',
                        data: res.data.userId
                      });
                      self.setData({
                        userID: res.data.userId
                      })
                      console.log(res);
                      console.log(getApp().globalData.userID);
                      console.log(getApp().globalData.openID)
                      console.log('78798')
                      wx.request({
                        url: 'https://localhost:80/admins/query',
                        data: {
                          adminId: res.data.userId
                        },
                        header: {
                          'content-type': 'application/json'
                        },
                        method: 'post',
                        success(res) {
                          console.log('test--------------------------------test');
                          console.log(res.data);
                          getApp().globalData.vipState = res.data.adminRole;
                        }
                      });
                    },
                    error: res => {
                      wx.showModal({
                        title: '温情提示',
                        content: '亲，因为网络原因，请稍后重试',
                        text: 'center',
                        complete() {}
                      });
                    }
                  })
                },
                fail(res) {
                  console.log('用户未授权');
                }
              })
            }
          }
        })
      }
    })

    // var BMap = new bmap.BMapWX({
    //   ak: self.data.ak,
    // });
    // var fail = function (data) {
    //   console.log(data);
    // };
    // var success = function (data) {
    //   //返回数据内，已经包含经纬度
    //   console.log(data.originalData.result.addressComponent.city + data.originalData.result.addressComponent.district + data.originalData.result.addressComponent.street + data.originalData.result.addressComponent.street_number);
    //   //使用wxMarkerData获取数据
    //   var wxMarkerData = data.originalData.result.addressComponent.city + data.originalData.result.addressComponent.district + data.originalData.result.addressComponent.street + data.originalData.result.addressComponent.street_number;
    //   //把所有数据放在初始化data内
    //   self.setData({
    //     addressData: wxMarkerData,
    //   });
    // }
    wx.request({
      url: self.urlChange(this.data.toView, this.data.num),
      methods: 'GET',
      success: res => {
        // console.log(res.data.list); 
        self.setData({
          detail: res.data.list,
        })
        // console.log(self.data.detail);
        self.incise();
        // console.log('hahah');
        // console.log(this.data.detail);
      },
      error: res => {
        console.log('请求失败！');
      },
    })
    wx.request({
      url: 'https://localhost:80/goods/state/2/1/goods',
      // data: {},
      method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      // header: {}, // 设置请求的 header
      success: function (res) {
        // success
        console.log('hahahahahahah-------hahahahahha');
        // console.log(res);
        self.setData({
          vipList: res.data.list,
        })
        console.log(self.data.vipList);
      },
      fail: function () {
        // fail
        console.log('成功')
      },
      complete: function () {
        // complete
      }
    })
    // 发起regeocoding检索请求 
    // BMap.regeocoding({
    //   fail: fail,
    //   success: success
    // })
  },

  //切割图片字符串函数
  incise() {
    let self = this;
    for (let index in self.data.detail) {
      //整合了arr数组存放了正确的图片地址
      let str = self.data.detail[index].goods.goodsImg;
      let s = "detail[" + index + "].goods.goodsImg";
      let arr = str.split(',');
      // for(let i in arr){
      //   let item = arr[i];
      //   let answear = 'https://www.zhaoshenma.cn:80/images/' + item;
      //   arr[i] = answear;
      // }
      self.setData({
        [s]: arr,
      })

    }
    console.log(self.data.detail);
  },


  //下滑刷新函数

  loadMore() {
    let self = this;
    console.log('下滑刷新');
    if (self.data.ifnum) {
      if (self.data.toView != 'hot') {
        self.setData({
          num: self.data.num + 1
        })
        self.request();
      }
    }
  },
  //选择地址
  // getLocation() {
  //   wx.chooseLocation({
  //     success: function (res) {
  //       console.log(res);
  //     },
  //   })
  // },
  //设置url函数
  urlChange(id, num) {
    return 'https://localhost:80/goods/' + id + '/' + num + '/goods';
  },

  //请求goods函数
  request() {
    // let self = this;
    wx.request({

      url: this.urlChange(this.data.toView, this.data.num),
      methods: 'GET',
      success: res => {
        console.log(res);
        if (res.statusCode == 200) {
          console.log('成功');
          //添加列表
          if (res.data.list == null) {
            this.setData({
              ifnum: false
            })
          } else if (res.data.list.length < 6) {
            this.setData({
              ifnum: false
            });
          }
          this.setData({
            detail: this.data.detail.concat(res.data.list)
          })

          console.log(this.data.detail);
          // self.calprice();
        } else {
          console.log("index.js wx.request CheckCallUser statusCode" + res.statusCode);
        }
      },
      error: () => {
        console.log('失败！');
      }
    })
  },

  //跳转函数
  jumpTo(e) {
    let self = this;
    console.log('准备跳转');
    console.log(e.currentTarget.dataset.index);
    let num = e.currentTarget.dataset.index;
    let id = self.data.detail[num].goods.goodsId;
    wx.navigateTo({
      url: '../component/details/details?goodsId=' + id,

      success: function (res) {
        // success
        console.log('成功跳转');
      },
      fail: function () {
        // fail
        console.log('跳转失败');
      },
      complete: function () {
        // complete
        console.log('已请求');
      }
    })
  },

  // 跳转函数
  jumpTo2(e) {
    let self = this;
    console.log('准备跳转');
    console.log(e.currentTarget.dataset.index);
    let num = e.currentTarget.dataset.index;
    let id = self.data.vipList[num].goods.goodsId;
    wx.navigateTo({
      url: '../component/details/details?goodsId=' + id,

      success: function (res) {
        // success
        console.log('成功跳转');
      },
      fail: function () {
        // fail
        console.log('跳转失败');
      },
      complete: function () {
        // complete
        console.log('已请求');
      }
    })
  },
  //加购物车
  addshop(e) {
    let that = this;
    // console.log(e.currentTarget);
    console.log(e.target.dataset.index);
    let index = e.target.dataset.index;

    console.log(that.data.detail[index]);
    let item = that.data.detail[index];
    // console.log(item);
    // console.log(app.globalData.userID);
    let vip = getApp().globalData.vipState;
    let price = 0;
    if(vip == 1){
      price = item.goods.goodsPrice;
    }
    else{
      price = item.newPrice;
    }
    let userId = null;
    console.log(price);   
    if (that.data.userID == null) {
      userId = wx.getStorageSync('userID');
    } else {
      userId = that.data.userID;
    }
    wx.request({
      url: 'https://localhost:80/cart/add',
      method: 'POST',
      data: {
        'cartGoods': {
          'goodsId': item.goods.goodsId,
          'goodsPrice': item.goods.goodsPrice
        },
        'cartNum': 1,
        'cartPrice': price,
        'cartUser': userId,
      },
      success: res => {
        console.log('成功');
        wx.showToast({
          title: '添加成功',
          icon: 'success',
          duration: 500
        })
      },
      error: res => {
        console.log('失败！');
        wx.showToast({
          title: '添加失败',
          icon: 'none',
          duration: 500
        })
      }

    })
  },

   //加购物车
   addshop2(e) {
    let that = this;
    // console.log(e.currentTarget);
    console.log(e.target.dataset.index);
    let index = e.target.dataset.index;

    console.log(that.data.vipList[index]);
    let item = that.data.vipList[index];
    // console.log(item);
    // console.log(app.globalData.userID);
    let vip = getApp().globalData.vipState;
    let price = 0;
    if(vip == 1){
      price = item.goods.goodsPrice;
    }
    else{
      price = item.newPrice;
    }
    let userId = null;
    console.log(price);   
    if (that.data.userID == null) {
      userId = wx.getStorageSync('userID');
    } else {
      userId = that.data.userID;
    }
    wx.request({
      url: 'https://localhost:80/cart/add',
      method: 'POST',
      data: {
        'cartGoods': {
          'goodsId': item.goods.goodsId,
          'goodsPrice': item.goods.goodsPrice
        },
        'cartNum': 1,
        'cartPrice': price,
        'cartUser': userId,
      },
      success: res => {
        console.log('成功');
        wx.showToast({
          title: '添加成功',
          icon: 'success',
          duration: 500
        })
      },
      error: res => {
        console.log('失败！');
        wx.showToast({
          title: '添加失败',
          icon: 'none',
          duration: 500
        })
      }

    })
  },


  //点击跳转分类
  category(e) {
    let index = e.target.dataset.index;
    let id = e.target.dataset.id;
    console.log(index);
    console.log(id);
    getApp().globalData.toView = index;
    getApp().globalData.curIndex = id;
    getApp().globalData.click = 'true';
    wx.switchTab({
      url: '../component/category/category',
      success: function (res) {
        // success
        console.log('成功跳转');
      },
      fail: function () {
        // fail
        console.log('跳转失败');
      },
      complete: function () {
        // complete
        console.log('已请求');
      }
    })
  },

  category2() {
    wx.showToast({
      title: '暂无商品上架，敬请期待',
      icon: 'none',
      duration: 2000
    })
  }

})